import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Student } from './models/student.entity';
import { DeepPartial, Repository } from 'typeorm';
// Repository是一个提供数据库操作的工具库
@Injectable()
export class StudentService {
  // 注入Student实体
  constructor(
    @InjectRepository(Student) private StudentRepository: Repository<Student>,
  ) {}
  // 返回值是promise对象
  // DeepPartial是一个将实体（Student）内部的所有属性加上?，即可以省略
  async create(entity: DeepPartial<Student>): Promise<boolean> {
    // const res = await this.StudentRepository.insert(entity);//insert方法不会触发create事件
    const res = await this.StudentRepository.save(
      this.StudentRepository.create(entity), //create仅仅是创建一个内存实体，没有放入数据库
    ); //
    // console.log('res', res);
    if (res) {
      return true;
    }
    return false;
  }

  // 删除用户
  async del(id: string): Promise<boolean> {
    const res = await this.StudentRepository.delete(id);
    // console.log('res', res);
    if (res && res.affected && res.affected > 0) {
      return true;
    }
    return false;
  }
  // 修改用户
  async updateById(id: string, entity: DeepPartial<Student>): Promise<boolean> {
    const res = await this.StudentRepository.update(id, entity);
    // console.log('res', res);
    if (res && res.affected && res.affected > 0) {
      return true;
    }
    return false;
  }
  // 查询用户
  async findById(id: string): Promise<Student | null> {
    const res = await this.StudentRepository.findOne({
      where: {
        id: id,
        // ...entity
      },
    });
    // console.log('res', res);
    return res;
  }
  // 通过手机查询用户
  async findByTel(tel: string): Promise<Student | null> {
    const res = await this.StudentRepository.findOne({
      where: {
        tel: tel,
        // ...entity
      },
    });
    // console.log('res', res);
    return res;
  }
  // 批量找学生
  async findStudents({
    start,
    size,
  }: {
    start: number;
    size: number;
  }): Promise<[Student[], number]> {
    console.log('批量找学生', { start, size });
    const res = this.StudentRepository.findAndCount({
      take: size,
      skip: start,
      order: {
        createAt: 'DESC',
      },
    });
    return res;
  }
}
